import React, { createContext, useContext, useState, ReactNode } from 'react';

interface ServerConfig {
  host: string;
  port: number;
}

interface ServerConfigContextType {
  serverConfig: ServerConfig;
  setServerConfig: (config: ServerConfig) => void;
  updateHost: (host: string) => void;
  updatePort: (port: number) => void;
}

const ServerConfigContext = createContext<ServerConfigContextType | undefined>(undefined);

export const useServerConfig = () => {
  const context = useContext(ServerConfigContext);
  if (context === undefined) {
    throw new Error('useServerConfig must be used within a ServerConfigProvider');
  }
  return context;
};

interface ServerConfigProviderProps {
  children: ReactNode;
}

export const ServerConfigProvider: React.FC<ServerConfigProviderProps> = ({ children }) => {
  const [serverConfig, setServerConfig] = useState<ServerConfig>({
    host: 'localhost',
    port: 9500
  });

  const updateHost = (host: string) => {
    setServerConfig(prev => ({ ...prev, host }));
  };

  const updatePort = (port: number) => {
    setServerConfig(prev => ({ ...prev, port }));
  };

  const value: ServerConfigContextType = {
    serverConfig,
    setServerConfig,
    updateHost,
    updatePort,
  };

  return (
    <ServerConfigContext.Provider value={value}>
      {children}
    </ServerConfigContext.Provider>
  );
};